import { JSEncrypt } from 'jsencrypt'
import { useEffect, useRef, useState } from 'react'
import { useTranslation } from 'react-i18next'
import { Button } from '../components/bs-ui/button'
import { Input } from '../components/bs-ui/input'
// import { alertContext } from "../contexts/alertContext";
import { useToast } from '@/components/bs-ui/toast/use-toast'
import { getCaptchaApi, getPublicKeyApi, loginApi, registerApi } from '../controllers/API/user'
import { captureAndAlertRequestErrorHoc } from '../controllers/request'
import CryptoJS from 'crypto-js'
const SECRET_KEY = 'cloud-migu-cooperation' // 请确保这个密钥安全且保密
import Logo from "@/assets/migu-logo-2.png"
import {Image} from "antd"
import { Eye, EyeOff, Lock, User } from "lucide-react"

export const LoginPage = () => {
  // const { setErrorData, setSuccessData } = useContext(alertContext);
  const { t, i18n } = useTranslation()
  const { message, toast } = useToast()

  const isLoading = false

  const mailRef = useRef(null)
  const pwdRef = useRef(null)
  const agenPwdRef = useRef(null)

  // login or register
  const [showLogin, setShowLogin] = useState(true)

  // captcha
  const captchaRef = useRef(null)
  const [captchaData, setCaptchaData] = useState({ captcha_key: '', user_capthca: false, captcha: '' })

  useEffect(() => {
    fetchCaptchaData()
  }, [])

  const fetchCaptchaData = () => {
    getCaptchaApi().then(setCaptchaData)
  }

  const handleLogin = async () => {
    const error = []
    const [mail, pwd] = [mailRef.current.value, pwdRef.current.value]
    if (!mail) error.push(t('login.pleaseEnterAccount'))
    if (!pwd) error.push(t('login.pleaseEnterPassword'))
    if (captchaData.user_capthca && !captchaRef.current.value) error.push(t('login.pleaseEnterCaptcha'))
    if (error.length) {
      return message({
        title: `${t('prompt')}`,
        variant: 'warning',
        description: error
      })
    }
    // if (error.length) return setErrorData({
    //     title: `${t('prompt')}:`,
    //     list: error,
    // });

    const encryptPwd = await handleEncrypt(pwd)
    captureAndAlertRequestErrorHoc(
      loginApi(mail, encryptPwd, captchaData.captcha_key, captchaRef.current?.value).then((res: any) => {
        // setUser(res.data)
        localStorage.setItem('ws_token', res.access_token)
        localStorage.setItem('isLogin', '1')
        location.href = '/chat'

        const dataToEncrypt = JSON.stringify({
          access_token_cookie: res.access_token
        })
        // 加密数据
        const encryptedData = CryptoJS.AES.encrypt(dataToEncrypt, SECRET_KEY).toString()

        const { protocol, hostname } = window.location;
        //const newPort = import.meta.env.VITE_BACKEND_PORT; // 新的端口
        const newPort = 13001
        const newBaseUrl = `${protocol}//${hostname}:${newPort}`;

        // 构建加密后的URL
        const urlWithEncryptedParam = `${newBaseUrl}?data=${encodeURIComponent(encryptedData)}`
        localStorage.setItem('admin-backend', urlWithEncryptedParam)
      })
    )

    fetchCaptchaData()
  }

  const handleRegister = async () => {
    const error = []
    const [mail, pwd, apwd] = [mailRef.current.value, pwdRef.current.value, agenPwdRef.current.value]
    if (!mail) {
      error.push(t('login.pleaseEnterAccount'))
    }
    if (mail.length < 3) {
      error.push(t('login.accountTooShort'))
    }
    if (!/.{8,}/.test(pwd)) {
      error.push(t('login.passwordTooShort'))
    }
    if (!/^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)(?=.*[\W_]).{8,}$/.test(pwd)) {
      error.push(t('login.passwordError'))
    }
    if (pwd !== apwd) {
      error.push(t('login.passwordMismatch'))
    }
    if (captchaData.user_capthca && !captchaRef.current.value) {
      error.push(t('login.pleaseEnterCaptcha'))
    }
    if (error.length) {
      return message({
        title: `${t('prompt')}`,
        variant: 'warning',
        description: error
      })
    }
    const encryptPwd = await handleEncrypt(pwd)
    captureAndAlertRequestErrorHoc(
      registerApi(mail, encryptPwd, captchaData.captcha_key, captchaRef.current?.value).then(res => {
        // setSuccessData({ title: t('login.registrationSuccess') })
        message({
          title: `${t('prompt')}`,
          variant: 'success',
          description: [t('login.registrationSuccess')]
        })
        pwdRef.current.value = ''
        setShowLogin(true)
      })
    )

    fetchCaptchaData()
  }

  const handleEncrypt = async pwd => {
    const { public_key } = await getPublicKeyApi()
    const encrypt = new JSEncrypt()
    encrypt.setPublicKey(public_key)
    return encrypt.encrypt(pwd) as string
  }

  return (
    <div className="h-full w-full login-page-bg bg-cover bg-center bg-no-repeat">
      <div className="fixed right-[0px] top-[50%] z-10 h-full w-full translate-x-[-20%] translate-y-[-50%] overflow-hidden rounded-lg border  shadow-xl sm:h-[520px] sm:w-[480px] ">
        <div className="absolute top-0 z-10 flex h-full w-full ">
          <div className="relative px-[20px] mx-auto ">
            <div className="py-2 px-1 mt-[100px]">
              <div className="flex items-center object-center">
              <img src={Logo} alt="Logo" width={100} height={100} className="mr-1 mt-[6px]" />
              <span className="text-violet-700 text-4xl">智算服务平台</span>
              </div>
            </div>
            <div className="mt-[100px] grid gap-[12px]">
              <div className="grid">
                <div className="relative">
                  <User className="absolute left-3 top-3.5 h-[22px] w-[22px] text-muted-foreground text-violet-700" />
                  <Input
                  id="email"
                  className="h-[48px] dark:bg-login-input pl-10"
                  ref={mailRef}
                  placeholder={t('login.account')}
                  type="email"
                  autoCapitalize="none"
                  autoComplete="email"
                  autoCorrect="off"
                  />
                </div>
              </div>
              <div className="grid pt-[10px]">
                <div className="relative">
                  <Lock className="absolute left-3 top-3 h-[22px] w-[22px] text-muted-foreground text-violet-700" />
                  <Input
                  id="pwd"
                  className="h-[48px] dark:bg-login-input pl-10"
                  ref={pwdRef}
                  placeholder={t('login.password')}
                  type="password"
                  onKeyDown={e => e.key === 'Enter' && showLogin && handleLogin()}
                  />
                </div>
                
              </div>
              {!showLogin && (
                <div className="grid">
                  <Input
                    id="pwd"
                    className="h-[48px] dark:bg-login-input"
                    ref={agenPwdRef}
                    placeholder={t('login.confirmPassword')}
                    type="password"
                  />
                </div>
              )}
              {captchaData.user_capthca && (
                <div className="flex items-center gap-4">
                  <Input
                    type="text"
                    ref={captchaRef}
                    placeholder={t('login.pleaseEnterCaptcha')}
                    className="form-input border border-gray-300 px-4 py-2 focus:outline-none"
                  />
                  <img
                    src={'data:image/jpg;base64,' + captchaData.captcha} // 这里应该是你的验证码图片的URL
                    alt="captcha"
                    onClick={fetchCaptchaData} // 这里应该是你的刷新验证码函数
                    className="h-10 cursor-pointer border border-gray-300 bg-gray-100"
                    style={{ width: '120px' }} // 根据需要调整宽度
                  />
                </div>
              )}
              {showLogin ? (
                <>
                
                  <Button className="mt-[32px] h-[48px] dark:bg-button" disabled={isLoading} onClick={handleLogin}>
                    {t('login.loginButton')}
                  </Button>
                </>
              ) : (
                <>
                  <div className="text-center">
                    <a
                      // href="javascript:;"
                      className="cursor-pointer text-sm text-blue-500 hover:underline"
                      onClick={e => {
                        e.preventDefault()
                        setShowLogin(true)
                      }}
                    >
                      {t('login.haveAccountLogin')}
                    </a>
                  </div>
                  <Button className="mt-[32px] h-[48px] dark:bg-button" disabled={isLoading} onClick={handleRegister}>
                    {t('login.registerButton')}
                  </Button>
                </>
              )}
            </div>
            <div className=" absolute bottom-[16px] right-[16px] flex">
              <div className="help flex"></div>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}
